/**
 * @description 用户画像》编辑用户
 *@author yhw
 */
import React, { Component, PropTypes } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Link } from 'dva/router';
import styles from './HomePage.less';
import MainLayout from '../components/MainLayout/MainLayout';
import {Table,Modal,Icon,Button,Radio,Form,Input} from 'antd';
import error from '../utils/tips';
import Cookie from '../utils/mcookie';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"), hash = window.location.hash;
  var r = hash.substring(hash.indexOf('?')+1).match(reg);
  if (r != null) return unescape(unescape(r[2])); return null;
}

let currentPageNo = 1;

class UserEdit extends Component {
	constructor(props) {
	    super(props);
	    this.state = {visible: false, modalTitle:'添加新用户', passwordDirty: false, userid:"",uname:"", email:"", telephone:"", usertype: "D"};
	}

	fetchData(type, search){
		this.props.dispatch({
		        type: type,
		        payload: search
		})
	};

	componentWillMount() {
		this.initData();
		
	};

	initData(){
		// 获取用户的基本信息
		this.fetchData('UserEdit/openidQuery', 'openId='+getQueryString("openid"));
		// 获取管理员用户列表
		this.fetchData('UserEdit/getUserList', 'pageSize=10&pageNum=1');
	};

	modifyPass(){
		let old=this.refs.oldPass.value, new1=this.refs.newPass.value, new2=this.refs.newPass2.value;
		if(old=="" || new1==""){
			error("密码不能为空");
		}else if(new1 != "" && new1!=new2){
			error("两次密码不一致");
		}else{
			this.fetchData('UserEdit/updateUserPassword', 'newpassword='+new1+"&id="+Cookie.get("userid"));
		}
	};

	addUser(){
		this.setState({
		      visible: true,
		      userid:"",
		      modalTitle:'添加新用户',
		      uname: '',
		      email:'',
		      telephone:'',
		      usertype:'D'
		});
	};

	editUser(e){
		this.setState({
		      visible: true,
		      modalTitle:'修改用户',
		      userid:e.id,
		      uname: e.username,
		      email:e.email,
		      telephone:e.phone,
		      usertype:e.user_type
		});
	};

	delUser(e){
		this.fetchData('UserEdit/deleteUser', 'userId='+e);
		this.fetchData('UserEdit/getUserList', 'pageSize=10&pageNum=1');
	}

	// 只是展示
	handleOk() {
	    //console.log('Clicked OK');
	    this.setState({
	      visible: false,
	    });
	};

	handleCancel(e) {
	    this.setState({
	      visible: false,
	    });
	};

	handleSubmit(e) {
	    e.preventDefault();
	    this.props.form.validateFieldsAndScroll((err, values) => {
	      if (!err) {
	        //console.log('form里接受到的值: ', values);
	        this.fetchData('UserEdit/'+(values.userid?'updateUserInfo':'addUserInfo'), values);
	        setTimeout(()=>{
	        	if(this.props.UserEdit.updateUserInfoResult){
		        	// 修改成功后，关闭浮层，刷新列表（修改-当前页）（添加-首页）
		        	this.handleCancel();
		        	this.fetchData('UserEdit/getUserList', 'pageSize=10&pageNum='+(values.userid?currentPageNo:1));
		}
	        }, 2500)
	      }
	    });
	};

	handlePasswordBlur(e) {
	    const value = e.target.value;
	    this.setState({ passwordDirty: this.state.passwordDirty || !!value });
	  };
	  checkPassowrd(rule, value, callback) {
	    const form = this.props.form;
	    if (value && value !== form.getFieldValue('password')) {
	      callback('两次密码不一致');
	    } else {
	      callback();
	    }
	  };
	  checkConfirm(rule, value, callback) {
	    const form = this.props.form;
	    if (value && this.state.passwordDirty) {
	      form.validateFields(['confirm'], { force: true });
	    }
	    callback();
	  };

	render(){
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
		      labelCol: { span: 6 },
		      wrapperCol: { span: 14 },
		};

		const columns = [{
		  title: '序号',
		  dataIndex: 'id',
		  //render: text => <a href="#">{text}</a>,
		}, {
		  title: '用户名',
		  dataIndex: 'username',
		}, {
		  title: '邮箱',
		  dataIndex: 'email',
		}, {
		  title: '手机号',
		  dataIndex: 'displayname',
		}, {
		  title: '操作',
		  render: (text, record) => (
		    <span>
		    <a href="javascript:void(0)" onClick={this.editUser.bind(this,record)}>编辑</a>&nbsp;&nbsp;<a href="javascript:void(0)" onClick={this.delUser.bind(this,record.id)}>删除</a>
		    </span>
		  )
		}];
		const pagination = {
		  total: this.props.UserEdit.getUserListData.totalRecordSize,
		  onChange: (current) => {
		  	currentPageNo=current;
		    	this.fetchData('UserEdit/getUserList', 'pageSize=10&pageNum='+current);
		  },
		};
	return (
	    <MainLayout isShowLeft="showNo">
	    <div className={styles.wrap}>
	      	<div className={styles.userPanel}>
	      		<h2><span className={styles.userBase}></span>基本资料</h2>
	      		<ol>
	      			<li><div className={styles.head} style={{margin:"0", width:55, height:55}}></div></li>
	      			<li>&nbsp;&nbsp;&nbsp;&nbsp;名称：蜜丝佛陀</li>
	      			<li>&nbsp;&nbsp;&nbsp;&nbsp;邮箱：maxfactor@maxfactor.com.cn</li>
	      			<li>手机号：13231002014</li>
	      		</ol>
	      	</div>
	      	<div className={styles.userPanel}>
	      		<h2><span className={styles.userModify}></span>修改密码</h2>
	      		<ol>
	      			<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;原密码：<input ref="oldPass" type="password" /></li>
	      			<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;新密码：<input ref="newPass" type="password" /></li>
	      			<li>重复新密码：<input ref="newPass2" type="password" /><Button type="primary" onClick={this.modifyPass.bind(this)} className= {styles.modifybtn}>确认修改</Button></li>
	      		</ol>
	      	</div>
	      	<div className={styles.userPanel}>
	      		<h2 style={{marginBottom:20}}><span className={styles.userList}></span>用户列表<b>*以下内容仅管理员可见</b></h2>
	      		<div style={{width:'70%'}}>
	      		<div className={styles.userAddPanel}><span className={styles.user+" "+styles.userAdd}></span><a href="javascript:void(0)" onClick={this.addUser.bind(this)}>添加新用户</a></div>
	      		<Table className="overSpec" rowKey={record => record.id} columns={columns} dataSource={this.props.UserEdit.getUserListData.detail} pagination={pagination} />
	      		</div>
	      	</div>
	      	<Modal title={this.state.modalTitle} visible={this.state.visible} onOk={this.handleOk.bind(this)} onCancel={this.handleCancel.bind(this)}>
		          <Form horizontal onSubmit={this.handleSubmit.bind(this)}>
		          	        <FormItem
			          {...formItemLayout}
			        >
			          {getFieldDecorator('userid', {
			          	initialValue: this.state.userid
			          })(
			            <Input type="hidden" />
			          )}
			        </FormItem>
		          	        <FormItem
			          {...formItemLayout}
			          label={(
			            <span>用户名</span>
			          )}
			          hasFeedback
			        >
			          {getFieldDecorator('uname', {
			          	initialValue: this.state.uname,
			            rules: [{ required: true, message: '请输入用户名' }],
			          })(
			            <Input />
			          )}
			        </FormItem>
			       <FormItem
			          {...formItemLayout}
			          label="邮箱"
			          hasFeedback
			        >
			          {getFieldDecorator('email', {
			          	initialValue: this.state.email,
			            rules: [{			            	 
			              type: 'email', message: '邮箱格式不正确',
			            }, {
			              required: true, message: '请输入邮箱地址',
			            }],
			          })(
			            <Input />
			          )}
			        </FormItem>
			        <FormItem
			          {...formItemLayout}
			          label="手机号"
			        >
			          {getFieldDecorator('telephone', {
			          	initialValue: this.state.telephone,
			            rules: [{ required: true, message: '请输入手机号' }],
			          })(
			            <Input />
			          )}
			        </FormItem>
			        <FormItem
			          {...formItemLayout}
			          label="密码"
			          hasFeedback
			        >
			          {getFieldDecorator('password', {
			            rules: [{
			              required: true, message: '请输入密码',
			            }, {
			              validator: this.checkConfirm.bind(this),
			            }],
			          })(
			            <Input type="password" onBlur={this.handlePasswordBlur.bind(this)} />
			          )}
			        </FormItem>
			        <FormItem
			          {...formItemLayout}
			          label="确认密码"
			          hasFeedback
			        >
			          {getFieldDecorator('password2', {
			            rules: [{
			              required: true, message: '请再次输入密码',
			            }, {
			              validator: this.checkPassowrd.bind(this),
			            }],
			          })(
			            <Input type="password" />
			          )}
			        </FormItem>
			        <FormItem
			          {...formItemLayout}
			          label="用户权限"
			        >
			          {getFieldDecorator('usertype', {
			            initialValue: this.state.usertype,
			          })(
			            <RadioGroup>
			              <Radio value="D">普通用户</Radio>
			              <Radio value="A">管理员</Radio>
			            </RadioGroup>
			          )}
			        </FormItem>
			        <FormItem wrapperCol={{ span: 12, offset: 6 }}>
			          <Button type="primary" htmlType="submit">确定</Button>&nbsp;&nbsp;&nbsp;
			          <Button type="ghost" onClick={this.handleCancel.bind(this)}>取消</Button>
			        </FormItem>
			      </Form>
		</Modal>
	     </div>
	    </MainLayout>
	  );
	}
}

function mapStateToProps({UserEdit}){
	return {UserEdit: {...UserEdit}}
}

UserEdit = Form.create({})(UserEdit);

export default connect(mapStateToProps)(UserEdit)